package com.huangmb.anymark.server.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huangmb.anymark.server.model.Category;
import com.huangmb.anymark.server.model.Marker;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 高德云图操作的工具类
 * @author hmb
 * @version 1.0
 * @since 2016/5/7 0:09
 */
public class CloudMapUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloudMapUtils.class);
    public static final String KEY = "6a9ebca37447d9830e48a0510b247ae4";
    public static final String TABLE_ID = "57277e6d305a2a09f99079fb";

    /**
     * 搜索用户位置的附近标注
     * @param lat 用户位置的纬度
     * @param lon 用户位置的经度
     * @param radius 搜索半径
     * @param keyword 关键字 可选
     * @param filter 过滤条件
     * @param page 分页大小
     * @return 搜索结果集
     */
    public static List<Marker> nearby(double lat, double lon, int radius, String keyword,String filter, int page) {
        try {
            String url = "http://yuntuapi.amap.com/datasearch/around";
            String center = String.format("%.6f,%.6f", lon, lat);
            Connection connection = createConnection(url)
                    .data("center", center)
                    .data("radius", String.valueOf(radius))
                    .data("limit", "20")
                    .data("page", String.valueOf(page));
            if (keyword != null) {
                connection.data("keywords", keyword);
            }
            if(filter != null){
                connection.data("filter",filter);
            }

            String res = connection.get().text();//从高德云图API返回的数据
            LOGGER.debug(res);
            JSONObject obj = JSON.parseObject(res);
            if(obj != null && obj.getInteger("status") == 1){//表示请求成功
                List<Marker> list = new ArrayList<>();
                JSONArray array = obj.getJSONArray("datas");//解析数据
                for (int i = 0 ; i <  array.size();i++){
                    obj = array.getJSONObject(i);
                    int id = Converter.toInt(obj.get("marker_id"),0);
                    String title = obj.getString("_name");
                    String info = obj.getString("info");

                    int create_time = Converter.toInt(obj.get("create_time"),0);
                    String address = obj.getString("_address");
                    //int distance = obj.getInteger("_distance");
                    int type_id = Converter.toInt(obj.get("type_id"),-1);
                    String type = obj.getString("type");
                    String[] location = obj.getString("_location").split(",");
                    double longitude = Double.valueOf(location[0]);
                    double latitude = Double.valueOf(location[1]);
                    Category category = new Category();
                    category.setId(type_id);
                    category.setName(type);

                    Marker marker = new Marker();//将返回的数据封装到Marker对象中
                    marker.setId(id);
                    marker.setTitle(title);
                    marker.setInfo(info);
                    marker.setCreateTime(create_time);
                    marker.setLatitude(latitude);
                    marker.setLongitude(longitude);
                    marker.setAddress(address);
                    marker.setCategory(category);

                    list.add(marker);


                }
                return list;
            }

        } catch (Exception e) {
           LOGGER.warn("云图搜索失败",e);
        }
        return null;
    }

    /**
     * 向高德云图请求创建一条新的标注
     *
     * @param marker 标注数据
     * @return 创建成功返回云图id，失败为null
     */
    public static String create(Marker marker) {
        String url = "http://yuntuapi.amap.com/datamanage/data/create";
        JSONObject obj = request(url, marker, null);
        if (obj != null && obj.getInteger("status") == 1) {
            return obj.getString("_id");
        }
        return null;
    }

    /**
     * 更新指定id的标注
     *
     * @param marker 新数据
     * @param id     云图id
     * @return true 更新成功 false 更新失败
     */
    public static boolean update(Marker marker, String id) {
        String url = "http://yuntuapi.amap.com/datamanage/data/update";
        JSONObject obj = request(url, marker, id);
        return obj != null && obj.getInteger("status") == 1;
    }

    /**
     * 删除数据
     *
     * @param id 云图id，多个id用逗号隔开
     * @return true 删除成功 false 删除失败
     */
    public static boolean delete(String id) {
        String url = "http://yuntuapi.amap.com/datamanage/data/delete";
        try {
            String res = createConnection(url)
                    .data("ids", id)
                    .post().text();
            System.out.println(res);
            JSONObject obj = JSON.parseObject(res);
            return obj != null && obj.getInteger("status") == 1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 发起网络请求
     * @param url 请求地址
     * @param marker 请求数据
     * @param id 数据id
     * @return 请求结果
     */
    private static JSONObject request(String url, Marker marker, String id) {
        JSONObject obj = new JSONObject();
        obj.put("_name", marker.getTitle());
        obj.put("_location", marker.getLongitude() + "," + marker.getLatitude());
        obj.put("_address", marker.getAddress());
        obj.put("info", marker.getInfo());
        obj.put("marker_id",""+marker.getId());
        obj.put("create_time", marker.getCreateTime());
        obj.put("type_id", marker.getCategory().getId());
        obj.put("type", marker.getCategory().getName());
        if (id != null) {
            obj.put("_id", id);
        }
        try {
            String res = createConnection(url)
                    .data("data", obj.toString())
                    .post().text();
            System.out.println(res);
            return JSON.parseObject(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建http连接对象
     * @param url 请求地址
     * @return http连接对象
     */
    private static Connection createConnection(String url) {
        return Jsoup.connect(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .data("key", KEY)
                .data("tableid", TABLE_ID)
                .ignoreContentType(true);
    }
}
